// 发送ajax请求的函数封装模块，返回一个pormise对象
import axios from 'axios'

export default function ajax(url='', data={}, method='GET') {
  return new Promise((resolve, reject) => {
    let promise
    if(method==='GET'){
      let dataString = ''
      Object.keys(data).forEach(key =>{
        const value = data[key]
        dataString += key + '=' +value + '&'
      })
      if (dataString){
        dataString = dataString.substring(0, dataString.length-1);
        url = url +"?" +dataString
      }
      promise = axios.get(url,data)
    }else {
      promise = axios.post(url, data)
    }

    promise.then(response => {
      resolve(response.data) //调用ajax函数的结果是直接是数据
    }).catch(error => {
      reject(error)
    })
  })
}


// ajax('/login', {name:'tom',pwd:'123'},'post').then(response => {
//   const result = response.data
// })

// const result = await ajax('/login', {name:'tom',pwd:'123'},'POST')
